package com.springcloud.command;

import com.netflix.hystrix.HystrixCollapser;
import com.netflix.hystrix.HystrixCollapserKey;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import org.assertj.core.util.Lists;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

public class CommandCollapser extends HystrixCollapser<List<String>, String, Integer> {

    private Integer id;

    public CommandCollapser(Integer id) {
        super(Setter.withCollapserKey(HystrixCollapserKey.Factory.asKey("CommandCollapser")));
        this.id = id;
    }

    @Override
    public Integer getRequestArgument() {
        return id;
    }

    @Override
    protected HystrixCommand<List<String>> createCommand(Collection<CollapsedRequest<String, Integer>> collapsedRequests) {
        return null;
    }

    @Override
    protected void mapResponseToRequests(List<String> batchResponse, Collection<CollapsedRequest<String, Integer>> collapsedRequests) {

    }

    class BatchCommand extends HystrixCommand<List<String>> {

        private Collection<CollapsedRequest<String,Integer>> collection;

        public BatchCommand(Collection<CollapsedRequest<String,Integer>> collection) {
            super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("BatchCommand")));
            this.collection = collection;
        }

        @Override
        protected List<String> run() throws Exception {
            System.out.println("currentthread："+Thread.currentThread().getName());
            ArrayList<String> result = Lists.newArrayList();

            Iterator<CollapsedRequest<String, Integer>> iterator = collection.iterator();
            while(iterator.hasNext()) {
                CollapsedRequest<String, Integer> next = iterator.next();
                Integer reqParam = next.getArgument();
                result.add("request:"+reqParam);
            }
            return result;
        }
    }
}
